/* -----------------
* brief
* 1. this is code gen by tools
* 2. mvc code are driver by the model defined with the same filename,
	 for example:
	 there is a Xmodel struct define in xmodel.go file, after the script run (lego model-mvc module_name xmodel)
     it will auto create the code under the module's path
	 m --> xmodel.go
	 v --> view
	 c --> xmodel_ctrl
* 3. you should modify this code if it doesn't satisfy your purpose
*/

package controller

import (
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"github.com/valyala/fasthttp"
	"saas_sys_base/common"

	. "saas_sys_base/modules/appmanager/models"
	. "saas_sys_base/modules/appmanager/service"
)

type AppProductSpecCtrl struct {
	service AppProductSpecService
}

func init() {
	vc := new(AppProductSpecCtrl)
	_ctrlList = append(_ctrlList, vc)
}

func (vc *AppProductSpecCtrl) CtrlInfo() string {
	return "AppProductSpecCtrl"
}

func (vc *AppProductSpecCtrl) RoutInit() {
	// 列表页面
	lego.GET("/admin/AppProductSpec/listpage", vc.ListPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	lego.GET("/admin/AppProductSpec/listjson", vc.ListJson, lego.LEGO_SESSION_TYPE_ADMIN, false)
	// 编辑页面
	lego.GET("/admin/AppProductSpec/editpage", vc.GetEditPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	lego.POST("/admin/AppProductSpec/editpage", vc.PostEditPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	// 删除
	lego.POST("/admin/AppProductSpec/del", vc.DelRecode, lego.LEGO_SESSION_TYPE_ADMIN, false)

	//获取商品规格列表
	lego.GET("/admin/AppProductSpec/GetProductSpecListJson", vc.ProductSpecListJson, lego.LEGO_SESSION_TYPE_WEB, true)
}

/* 列表接口
* params:
  ---
*/
func (vc *AppProductSpecCtrl) ListJson(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		//:saas管理端使用代码，使用时将注释解开 sessionData := common.GetSessionData(&ctxExt)
		//:appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			Keyword string // 关键字查询
			Page    int    `vd:"$>0"` // 分页
			PSize   int    `vd:"$>0"` // 分页大小

			OrderField string
			Order      string `vd:"$=='' || $=='asc' || $=='desc'"`
			ProductId  int64
		}
		req := ReqParams{
			Keyword:    string(ctxExt.Peek("keyword")),
			Page:       utils.BytesToInt(ctxExt.Peek("page")),
			PSize:      utils.BytesToInt(ctxExt.Peek("limit")),
			OrderField: string(ctxExt.Peek("order_field")),
			Order:      string(ctxExt.Peek("order")),
			ProductId: utils.BytesToInt64(ctxExt.Peek("product_id")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务查询
		if list, total, err := vc.service.ListAppProductSpec(req.ProductId, req.Keyword, req.Page, req.PSize, req.OrderField, req.Order); err != nil {
			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 列表接口
* params:
  ---
*/
func (vc *AppProductSpecCtrl) ProductSpecListJson(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			ProductId  int64
		}
		req := ReqParams{
			ProductId: utils.BytesToInt64(ctxExt.Peek("product_id")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务查询
		if list, total, err := vc.service.ListAppProductSpecByWhoAndProductId(appwho, req.ProductId); err != nil {
			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *AppProductSpecCtrl) ListPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("appmanager/view/AppProductSpec/list.html", data)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *AppProductSpecCtrl) GetEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		target := vc.service.GetAppProductSpecById(req.Id)
		data["detail"] = target
		break
	}
	ctxExt.HTML("appmanager/view/AppProductSpec/edit.html", data)
	return
}

/* 数据编辑
* params:
  ---
*/
func (vc *AppProductSpecCtrl) PostEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""

	for {
		//:saas管理端使用代码，使用时将注释解开 sessionData := common.GetSessionData(&ctxExt)
		//:appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			//#ModelEditFormDefined#
			Id        int64   `vd:""`
			IfDel     int     `vd:""`
			Cdate     string  `vd:""`
			Udate     string  `vd:""`
			SpecName  string  `vd:""`
			SellPrice float64 `vd:""`
			Stock     int     `vd:""`
			ProductId int64   `vd:""`
			Months    int     `vd:""`
		}
		req := ReqParams{
			//#ModelEditFormFiled#
			Id:        utils.BytesToInt64(ctxExt.Peek("id")),
			IfDel:     utils.BytesToInt(ctxExt.Peek("if_del")),
			Cdate:     string(ctxExt.Peek("cdate")),
			Udate:     string(ctxExt.Peek("udate")),
			SpecName:  string(ctxExt.Peek("spec_name")),
			SellPrice: utils.BytesToFloat64(ctxExt.Peek("sell_price")),
			Stock:     utils.BytesToInt(ctxExt.Peek("stock")),
			ProductId: utils.BytesToInt64(ctxExt.Peek("product_id")),
			Months:    utils.BytesToInt(ctxExt.Peek("months")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务处理
		recode := vc.service.GetAppProductSpecById(req.Id)
		if recode == nil {
			// 新建
			recode := new(AppProductSpec)
			//#ModelFiledMapper#'
			recode.Id = req.Id
			recode.IfDel = req.IfDel
			recode.Cdate = req.Cdate
			recode.Udate = req.Udate
			recode.SpecName = req.SpecName
			recode.SellPrice = req.SellPrice
			recode.Stock = req.Stock
			recode.ProductId = req.ProductId
			recode.Months = req.Months

			if false == vc.service.SaveAppProductSpec(recode) {
				code = 100
				msg = "false"
				break
			}
		} else {
			//#ModelFiledMapper#
			recode.Id = req.Id
			recode.IfDel = req.IfDel
			recode.Cdate = req.Cdate
			recode.Udate = req.Udate
			recode.SpecName = req.SpecName
			recode.SellPrice = req.SellPrice
			recode.Stock = req.Stock
			recode.ProductId = req.ProductId
			recode.Months = req.Months

			if false == vc.service.UpdateAppProductSpec(recode) {
				code = 100
				msg = "false"
				break
			}
		}
		break
	}
	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

/* 删除数据记录
* params:
  ---
*/
func (vc *AppProductSpecCtrl) DelRecode(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""
	for {
		// 表单校验
		type ReqParams struct {
			Id int64 `vd:"$>0"` // 记录id
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		// 业务删除
		target := vc.service.GetAppProductSpecById(req.Id)
		if target == nil {
			code = 100
			msg = "记录不存在"
			break
		}

		if false == vc.service.DelAppProductSpecById(target.Id) {
			code = 100
			msg = "操作失败"
			break
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}
